package persistence.dao;

import java.awt.Color;
import java.sql.ResultSet;
import java.sql.SQLException;


import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.*;

public class MatiereDAO extends AbstractDAO{
	
	private Matiere matiere;

	/**
	 * Constructeur d'une matiere DAO
	 */
	public MatiereDAO() {
		setTableName("MATIERE");
	}

	/**
	 * Constructeur d'une matiere DAO
	 * @param mat matiere associee
	 */
	public MatiereDAO(Matiere mat){
		this();
		matiere = mat;
		setId(matiere.getId());
	}
	
	public Matiere getMatiere() {
		return matiere;
	}

	public void setMatiere(Matiere matiere) {
		this.matiere = matiere;
	}

	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		try {
			setId(rset.getInt("id_Matiere"));
			
			DataSet seeSet = SEE.all().filter("FK_SEE_MATIERE = " + getId());
			
			return new Matiere(getId(),
					rset.getString("nomMatiere"),
					rset.getString("descriptionMatiere"),
					rset.getFloat("coeffDivise"),
					new Color(Integer.parseInt(rset.getString("couleur"), 16)),
					rset.getInt("FK_MATIERE_UE"),
					seeSet
					
					);
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		String query;
		ResultSet result;
			query = "INSERT INTO " + getTableName() +
			" VALUES ( S_PK_"+ getTableName() +".nextval, '" + matiere.getNomMatiere() +
			"', '" + matiere.getDescriptionMatiere() +
			"', " + matiere.getCoeffDivise() +
			", '" + Integer.toHexString(matiere.getCouleur().getRGB()).substring(2) +
			"', " + matiere.getIdUE() + ")";
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
			setId(this.getId()); /* Mise a jour de l'identifiant */
	}

	public void save(int id) {
		String query;
		ResultSet result;
			query = "UPDATE " + getTableName() +
				" SET nomMatiere = '" + matiere.getNomMatiere() +
				"', descriptionMatiere = '" + matiere.getDescriptionMatiere() +
				"', coeffDivise = " + matiere.getCoeffDivise() +
				", couleur = '" + Integer.toHexString(matiere.getCouleur().getRGB()).substring(2) +
				"', fk_matiere_ue = " + matiere.getIdUE() +
				" WHERE ID_"+ getTableName() + " = " + id;
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
	}
}
